package com.filter.control.common;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.stream.Collectors;


@Component
public class HttpProxyClient {

    /**
     * 创建新的请求
     * @param originalRequest
     * @param modifiedUrl
     * @return
     */
    private HttpServletRequest createNewRequest(HttpServletRequest originalRequest, String modifiedUrl) {

        // 根据请求方法创建新的请求对象
        CustomServletRequestWrapper newRequest;
        // 自定义Http请求对象
        if (originalRequest.getMethod().equalsIgnoreCase("POST")) {
            newRequest = new CustomServletRequestWrapper(originalRequest, modifiedUrl);
        } else {
            newRequest = new CustomServletRequestWrapper(originalRequest, modifiedUrl, "GET");
        }
        // 复制原始请求的参数
        Enumeration<String> parameterNames = originalRequest.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            String[] paramValues = originalRequest.getParameterValues(paramName);
            for (String paramValue : paramValues) {
                newRequest.getParameterMap().put(paramName, new String[]{paramValue});
            }
        }
        // 复制原始请求的请求头参数
        Enumeration<String> headerNames = originalRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            Enumeration<String> headerValues = originalRequest.getHeaders(headerName);
            while (headerValues.hasMoreElements()) {
                String headerValue = headerValues.nextElement();
                newRequest.addHeader(headerName, headerValue);
            }
        }
        // 复制会话标识符
        newRequest.getSession().invalidate();
        newRequest.getSession(true).setAttribute("JSESSIONID", originalRequest.getSession().getId());

        return newRequest;
    }


    /**
     * 发送请求
     * @param httpClient
     * @param request
     * @return
     * @throws IOException
     */
    public HttpResponse sendRequest(HttpClient httpClient, HttpServletRequest request, String url) throws IOException {

        System.out.println( " 获取请求url结果 " + request.getRequestURL().toString());
        // 根据请求方法发送请求
        if (request.getMethod().equalsIgnoreCase("POST")) {
            String requestBody = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            // 创建HttpPost对象
            HttpPost httpPost = new HttpPost(url);
            // 创建请求体实体
            StringEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
            // 设置请求体实体到HttpPost中
            httpPost.setEntity(entity);

            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = request.getHeader(headerName);
                httpPost.setHeader(headerName, headerValue);
            }
            return httpClient.execute(httpPost);
        } else {
            HttpGet httpGet = new HttpGet(url);
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = request.getHeader(headerName);
                httpGet.setHeader(headerName, headerValue);
            }
            return httpClient.execute(httpGet);
        }
    }

    /**
     * 发送请求
     * @param httpClient
     * @param request
     * @return
     * @throws IOException
     */
    private HttpResponse sendRequest(HttpClient httpClient, HttpServletRequest request) throws IOException {

        System.out.println( " 获取请求url结果 " + request.getRequestURL().toString());
        // 根据请求方法发送请求
        if (request.getMethod().equalsIgnoreCase("POST")) {
            String requestBody = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            // 创建HttpPost对象
            HttpPost httpPost = new HttpPost(request.getRequestURL().toString());
            // 创建请求体实体
            StringEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
            // 设置请求体实体到HttpPost中
            httpPost.setEntity(entity);

            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = request.getHeader(headerName);
                httpPost.setHeader(headerName, headerValue);
            }
            return httpClient.execute(httpPost);
        } else {
            HttpGet httpGet = new HttpGet(request.getRequestURL().toString());
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = request.getHeader(headerName);
                httpGet.setHeader(headerName, headerValue);
            }
            return httpClient.execute(httpGet);
        }
    }

    public String sendMessages(HttpServletRequest request, String url){
        String responseString = "";
        try {
            // 发送请求并获取响应
            HttpServletRequest copyReq = createNewRequest(request,  url);
            HttpClient httpClient = HttpClients.createDefault();
            HttpResponse response = sendRequest(httpClient, copyReq);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应结果转换为字符串
                responseString = EntityUtils.toString(responseEntity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseString;
    }


    public String sendMessagesNew(HttpServletRequest request, String url){
        String responseString = "";
        try {
            // 发送请求并获取响应
            HttpClient httpClient = HttpClients.createDefault();
            HttpResponse response = sendRequest(httpClient, request, url);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应结果转换为字符串
                responseString = EntityUtils.toString(responseEntity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseString;
    }



}
